package cn.edu.ujn.food.controller;

import cn.edu.ujn.food.entity.*;
import cn.edu.ujn.food.service.*;
import cn.edu.ujn.util.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@org.springframework.stereotype.Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RestaurantService restaurantService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private IngredientstockService ingredientstockService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderdetailService orderdetailService;
    @Autowired
    private TableService tableService;
    @Autowired
    private ReservationService reservationService;
    @Autowired
    private ReviewService reviewService;
    @Autowired
    private UsercouponService usercouponService;
    @GetMapping("/login")
    public String showLoginPage(Model model) {
        return "login";
    }

    @PostMapping("/login")
    public String check(User user, Model model, HttpServletRequest request){
        User user1 = userService.checkLogin(user);
        if(user1 != null){
            HttpSession session = request.getSession();
            session.setAttribute("USER",user1);
            return "user";
        }else{
            model.addAttribute("msg","用户名或密码错误！");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return "logout";
    }

    @GetMapping("/user")
    public String listUser(@RequestParam(value = "page",defaultValue = "1") Integer page,
                       @RequestParam(value = "row",defaultValue = "10") Integer rows, Model model, User user) {
        user.setStart((page-1)*rows);
        user.setRows(rows);
        Page<User> page1 = userService.selectAll(user);
        page1.setPage(page);
        model.addAttribute("page",page1);
        return "user";
    }

    @GetMapping("/user/{id}")
    @ResponseBody
    public ResponseEntity<User> getUserById(@PathVariable("id") Integer userId) {
        User user = userService.queryById(userId);
        if (user == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @PutMapping("/user/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable("id") Integer userId, @RequestBody User user) {
        try {
            user.setUserId(userId);
            userService.update(user);
            return ResponseEntity.ok(Map.of("success", true, "message", "用户信息已成功更新"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "更新失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/user/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable("id") Integer userId) {
        try {
            boolean isDeleted = userService.deleteById(userId);
            if (isDeleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "用户信息删除成功！"));
            } else {
                return new ResponseEntity<>(Map.of("success", false, "message", "用户信息删除失败，用户不存在或已删除。"), HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(Map.of("success", false, "message", "用户信息删除失败: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/user")
    @ResponseBody
    public String createUser(User user) {
        try {
            userService.insert(user);
            return "OK";
        } catch (Exception e) {
            return "FAIL";
        }
    }
}


